import axios from "axios";
import md5 from "js-md5";
import { Message } from "element-ui";
const http = axios.create({
  timeout: 1000 * 60 * 2,
  withCredentials: true,
});
// 2. 配置-统一请求接口网址
const require = axios.create({
  baseURL: "https://grandcanal-pro-api.d-y-h.cn/",
});
// 请求拦截器
require.interceptors.request.use((config) => {
  let getGuid = (len, radix) => {
    if (len == null || len == 0 || len == "" || len == undefined) {
      len = 32;
    }
    if (radix == null || radix == 0 || radix == "" || radix == undefined) {
      radix = 16;
    }
    let CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
      ""
    );
    let chars = CHARS,
      uuid = [],
      i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) {
        uuid[i] = chars[0 | (Math.random() * radix)];
      }
    } else {
      let r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = "‐";
      uuid[14] = "4";
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | (Math.random() * 16);
          uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join("");
  };
  //3
  let getNowTimestamp = () => {
    let timestamp = new Date()
      .getTime()
      .toString()
      .substr(0, 10);
    return timestamp;
  };
  let times = getNowTimestamp();
  let uuids = getGuid();
  config.headers["Ql-Auth-Timestamp"] = times;
  config.headers["Ql-Auth-Nonce"] = uuids;
  config.headers["Ql-Auth-Sign"] = md5(
    md5(uuids + times) + "abcdefg!@#12344321!777"
  );
  let data = JSON.parse(window.localStorage.getItem("params"));
  if (data !== null) {
    config.headers["Uid"] = data.Uid;
    config.headers["Open-Id"] = data.OpenId;
    config.headers["Skey"] = data.Skey;
  }
  return config;
});
// 响应拦截器
require.interceptors.response.use(
  (response) => {
    setTimeout(() => {
      // localStorage里面存的数据
      if (
        window.localStorage.getItem("params") === null ||
        response.data.code === "10038" ||
        response.data.code === "10001"
      ) {
        Message({
          message: "用户信息失效，请重新登录",
          type: "warning",
        });
        setTimeout(() => {
          window.location.href = "https://oss.d-y-h.cn/mp/oauth2/login";
        }, 1000);
      }
    }, 2000);
    return response;
  },
  function(error) {
    return Promise.reject(error);
  }
);
export default require;
